/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#import "AvoidModuleSpec.h"
#import "AvoidModule.h"
#import "AWSafeAreaMonitor.h"

@implementation AvoidModule

RCT_EXPORT_MODULE(RTNAvoidAreaRegion)

- (NSArray<NSString *> *)supportedEvents
{
    return @[ @"avoidAreaChange" ];
}

RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSDictionary *, getWindowAvoidArea : (int)type)
{
    NSString *json = [[AWSafeAreaMonitor shared] getWindowAvoidAreaForType:type];
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding]
                                                           options:kNilOptions
                                                             error:nil];
    return result;
}

RCT_EXPORT_METHOD(addAvoidAreaListener)
{
    dispatch_async(dispatch_get_main_queue(), ^{
      [[AWSafeAreaMonitor shared] addAvoidAreaListener:^(NSString *_Nonnull safeAreas) {
        // 获取模块实例并触发事件
        [self sendEventWithName:@"avoidAreaChange" body:safeAreas];
      }];
    });
}

RCT_EXPORT_METHOD(removeAvoidAreaListener)
{
    dispatch_async(dispatch_get_main_queue(), ^{
      [[AWSafeAreaMonitor shared] removeAvoidAreaListener];
    });
}

- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
    (const facebook::react::ObjCTurboModule::InitParams &)params
{
    return std::make_shared<facebook::react::NativeAvoidModuleSpecJSI>(params);
}
@end